//
//  ForgetPasswordVC.m
//  NoNeedle
//
//  Created by Ming Tian on 2017/3/8.
//  Copyright © 2017年 Ming Tian. All rights reserved.
//

#import "ForgetPasswordVC.h"

const double confirmButtonRate = 90.0f/450.0f;

@interface ForgetPasswordVC ()<UITextFieldDelegate>{
    
    NSArray * phoneArray;
    NSString * choose;
    UIImageView * moreImage;
}

@end

@implementation ForgetPasswordVC

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    choose = @"0";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = NavBackColor;
    self.navigationController.navigationBar.translucent = NO;
    [self createUI];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
    
    [self getUrgentRequest];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 发送验证码
- (void)verifyCodeAction {
    if(self.usernameTextField.text.length != 11) {
        [MBProgressHUD showMessag:@"请选择联系人" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        return;
    }
    
    [self openCountdown]; // 开启倒计时
    NSDictionary *parameter = @{@"username":self.usernameTextField.text,
                                @"type":@"forget"
                                };
    [PostNetWorking postNetWorkingStr:[address_url stringByAppendingString:user_signup_code_api] andparameters:parameter Success:^(id responseObject) {
        if([responseObject[@"code"]integerValue] == 200) {
            [MBProgressHUD showMessag:@"验证码已发送" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        }
        if([responseObject[@"code"]integerValue] == 210) {
            [MBProgressHUD showMessag:responseObject[@"mark"] withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        }
    } failed:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showMessag:@"网络错误" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
    }];
}

#pragma mark - 验证码倒计时
-(void)openCountdown{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.verifyButton setTitle:@"获取" forState:UIControlStateNormal];
                [self.verifyButton setTitleColor:themeColor forState:UIControlStateNormal];
                self.verifyButton.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.verifyButton setTitle:[NSString stringWithFormat:@"%.2ds", seconds] forState:UIControlStateNormal];
                [self.verifyButton setTitleColor:themeColor forState:UIControlStateNormal];
                self.verifyButton.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - 重置密码
- (void)resetPasswordAction {
    if(self.usernameTextField.text.length != 11) {
        [MBProgressHUD showMessag:@"请输选择联系人" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        return;
    }
    if(self.verifyTextField.text.length == 0) {
        [MBProgressHUD showMessag:@"请输入验证码" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        return;
    }
    if(self.passwordTextField.text.length == 0) {
        [MBProgressHUD showMessag:@"请输入密码" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        return;
    }
    if(self.passwordTextField.text.length < 6 || self.passwordTextField.text.length > 18) {
        [MBProgressHUD showMessag:@"密码长度为6-18位" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        return;
    }
    if(![self.passwordTextField.text isEqualToString:self.confirmPasswordTextField.text]) {
        [MBProgressHUD showMessag:@"两次密码不一致" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        return;
    }
    
    NSDictionary *parameter = @{@"contact":self.usernameTextField.text, @"password":self.passwordTextField.text, @"code":self.verifyTextField.text,@"username":self.phoneStr};
    MBProgressHUD *hud = [MBProgressHUD showMessag:@"正在重置密码" withDelay:1 toView:self.view withMode:MBProgressHUDModeIndeterminate hideWithDelay:0];
    [PostNetWorking postNetWorkingStr:[address_url stringByAppendingString:user_forgetPwd_api] andparameters:parameter Success:^(id responseObject) {
        hud.isContinue = NO;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        int code = [responseObject[@"code"]intValue];
        switch (code) {
            case 200:
            {
                //成功
                [MBProgressHUD showMessag:@"密码重置成功" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
                break;
            case 210:
            {
                //逻辑错误
                [MBProgressHUD showMessag:responseObject[@"mark"] withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            }
                break;
            default:
                break;
        }
    } failed:^(NSError *error) {
        hud.isContinue = NO;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showMessag:@"网络错误" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
    }];

}

#pragma mark - 界面布局
- (void)createUI {
    self.navigationItem.titleView = [TopLabel withLabelWithLabelText:@"忘记密码"];
    [self setupSubviews];
}
- (void)setupSubviews {
    self.usernameLeftImageView = [[UIImageView alloc]init];
    self.usernameLeftImageView.image = [UIImage imageNamed:@"icon_login_user"];
    [self.view addSubview:self.usernameLeftImageView];
    
    self.usernameTextField = [[UITextField alloc]init];
    self.usernameTextField.font = [UIFont systemFontOfSize:15];
    self.usernameTextField.placeholder = @"请选择联系人";
    self.usernameTextField.delegate = self;
    self.usernameTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.usernameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:self.usernameTextField];
    
    moreImage = [[UIImageView alloc]init];
    moreImage.image = ImageName(@"icon_user_more");
    [self.view addSubview:moreImage];
    
    self.verifyLeftImageView = [[UIImageView alloc]init];
    self.verifyLeftImageView.image = [UIImage imageNamed:@"icon_login_vc"];
    [self.view addSubview:self.verifyLeftImageView];
    
    self.verifyTextField = [[UITextField alloc]init];
    self.verifyTextField.font = [UIFont systemFontOfSize:15];
    self.verifyTextField.placeholder = @"验证码";
    self.verifyTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:self.verifyTextField];
    
    self.verifyButton = [[UIButton alloc]init];
    [self.verifyButton setTitleColor:themeColor forState:UIControlStateNormal];
    [self.verifyButton setTitle:@"获取" forState:UIControlStateNormal];
    self.verifyButton.layer.borderColor = themeColor.CGColor;
    self.verifyButton.layer.borderWidth = 1;
    self.verifyButton.layer.cornerRadius = 13;
    [self.verifyButton addTarget:self action:@selector(verifyCodeAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.verifyButton];
    
    self.passwordLeftImageView = [[UIImageView alloc]init];
    self.passwordLeftImageView.image = [UIImage imageNamed:@"icon_login_passworld"];
    [self.view addSubview:self.passwordLeftImageView];
    
    self.passwordTextField = [[UITextField alloc]init];
    self.passwordTextField.font = [UIFont systemFontOfSize:15];
    self.passwordTextField.placeholder = @"密码";
    self.passwordTextField.secureTextEntry = YES;
    self.passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:self.passwordTextField];
    
    self.confirmPasswordLeftImageView = [[UIImageView alloc]init];
    self.confirmPasswordLeftImageView.image = [UIImage imageNamed:@"icon_login_passworld"];
    [self.view addSubview:self.confirmPasswordLeftImageView];
    
    self.confirmPasswordTextField = [[UITextField alloc]init];
    self.confirmPasswordTextField.font = [UIFont systemFontOfSize:15];
    self.confirmPasswordTextField.placeholder = @"确认密码";
    self.confirmPasswordTextField.secureTextEntry = YES;
    self.confirmPasswordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:self.confirmPasswordTextField];
    
    self.confirmButton = [[UIButton alloc]init];
    self.confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.confirmButton setTitle:@"确认" forState:UIControlStateNormal];
    [self.confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.confirmButton.backgroundColor = themeColor;
    self.confirmButton.layer.cornerRadius = screenW*0.65*confirmButtonRate/2;
    self.confirmButton.layer.masksToBounds = NO;
    [self.confirmButton addTarget:self action:@selector(resetPasswordAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.confirmButton];
    // 按钮投影
    self.confirmButton.layer.shadowColor = themeColor.CGColor;
    self.confirmButton.layer.shadowOpacity = 0.6f;
    self.confirmButton.layer.shadowOffset = CGSizeMake(0,2);
    self.confirmButton.layer.shadowRadius = 4;
    
    self.sepLine1 = [[UIView alloc]init];
    self.sepLine1.backgroundColor = RGBa(0xe2e2e2);
    [self.view addSubview:self.sepLine1];
    self.sepLine2 = [[UIView alloc]init];
    self.sepLine2.backgroundColor = RGBa(0xe2e2e2);
    [self.view addSubview:self.sepLine2];
    self.sepLine3 = [[UIView alloc]init];
    self.sepLine3.backgroundColor = RGBa(0xe2e2e2);
    [self.view addSubview:self.sepLine3];
    self.sepLine4 = [[UIView alloc]init];
    self.sepLine4.backgroundColor = RGBa(0xe2e2e2);
    [self.view addSubview:self.sepLine4];

    [self setupConstraints];
}


-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if ( self.usernameTextField==textField) {
        
        [textField resignFirstResponder];
        
        NSLog(@"不弹出键盘");
        
        zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:phoneArray andHeadTitle:@"选择联系人" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
            self.usernameTextField.text = choiceString;
            choose = @"1";
            [pickerView dismissPicker];
        }];
        [pickerView show];
    }
    
}

- (void)setupConstraints {
    [self.sepLine1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(70+64);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.view).multipliedBy(0.75);
        make.height.mas_equalTo(1);
    }];
    [self.usernameLeftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.sepLine1).offset(10);
        make.bottom.equalTo(self.sepLine1).offset(-7);
        make.width.height.mas_equalTo(30);
    }];
    
    
    [self.usernameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.usernameLeftImageView.mas_right).offset(10);
        make.bottom.equalTo(self.usernameLeftImageView);
        make.right.equalTo(self.sepLine1);
        make.height.equalTo(self.usernameLeftImageView);
    }];
    
    [moreImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.usernameTextField.mas_right).offset(-20);
        make.bottom.equalTo(self.usernameLeftImageView);
        make.right.equalTo(self.sepLine1);
        make.height.equalTo(self.usernameLeftImageView);
    }];
    
    [self.verifyLeftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sepLine1).offset(7);
        make.left.equalTo(self.usernameLeftImageView);
        make.width.equalTo(self.usernameLeftImageView);
        make.height.equalTo(self.usernameLeftImageView);
    }];
    [self.verifyTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.verifyLeftImageView);
        make.left.equalTo(self.usernameTextField);
        make.right.equalTo(self.usernameTextField).offset(-60);
        make.height.equalTo(self.usernameTextField);
    }];
    [self.verifyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.verifyTextField);
        make.left.equalTo(self.verifyTextField.mas_right);
        make.right.equalTo(self.usernameTextField);
        make.height.equalTo(self.verifyTextField).offset(-4);
    }];
    [self.sepLine2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.verifyLeftImageView.mas_bottom).offset(7);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.sepLine1);
        make.height.equalTo(self.sepLine1);
    }];
    [self.passwordLeftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sepLine2).offset(7);
        make.left.equalTo(self.verifyLeftImageView);
        make.width.equalTo(self.verifyLeftImageView);
        make.height.equalTo(self.verifyLeftImageView);
    }];
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordLeftImageView);
        make.left.equalTo(self.verifyTextField);
        make.right.equalTo(self.sepLine2);
        make.height.equalTo(self.verifyTextField);
    }];
    [self.sepLine3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordLeftImageView.mas_bottom).offset(7);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.sepLine2);
        make.height.equalTo(self.sepLine2);
    }];
    [self.confirmPasswordLeftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sepLine3).offset(7);
        make.left.equalTo(self.passwordLeftImageView);
        make.width.equalTo(self.passwordLeftImageView);
        make.height.equalTo(self.passwordLeftImageView);
    }];
    [self.confirmPasswordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.confirmPasswordLeftImageView);
        make.left.equalTo(self.passwordTextField);
        make.right.equalTo(self.passwordTextField);
        make.height.equalTo(self.passwordTextField);
    }];
    [self.sepLine4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.confirmPasswordLeftImageView.mas_bottom).offset(7);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.sepLine3);
        make.height.equalTo(self.sepLine3);
    }];
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.sepLine4).offset(30);
        make.width.equalTo(self.view).multipliedBy(0.65);
        make.height.mas_equalTo(screenW*0.65*confirmButtonRate);
    }];


    
}


-(void)getUrgentRequest{
    
    NSDictionary * dic = @{@"username":self.phoneStr
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_urgentPhone_api) andparameters:dic Success:^(id responseObject) {
        if (codeSucess) {
            
            NSString * str  = responseObject[@"datas"][@"contact_1"];
            if (str ==nil||str.length<=0) {
                
                 phoneArray  = @[USER_DEFAULTGet(@"username")];
               
            }else {
                
                phoneArray  = @[responseObject[@"datas"][@"contact_1"],responseObject[@"datas"][@"contact_2"],USER_DEFAULTGet(@"username")];
            }
            
          
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBhudTextNetError;
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
